package com.atguigu.ossservice.service.impl;

import com.aliyun.oss.OSSClient;
import com.atguigu.baseservice.handler.GuliException;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.ossservice.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    //上传文件
    @Override
    public String uploadFileOSS(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String filename = file.getOriginalFilename();


        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);

        //上传文件流
        try {
            InputStream inputStream = file.getInputStream();
            filename = UUID.randomUUID().toString()+filename;
            String path = new DateTime().toString("yyyy/MM/dd");
            filename = path + "/" + filename;
            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();
            String url = "https://" + bucketName + "." + endPoint + "/" + filename;
            return url;
        } catch (IOException e) {
            throw new GuliException(20001,"上传失败");
        }

    }
}
